﻿using System;
using System.Collections;
using System.Data;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using Rison.DataAccess.Data.ZJCP;

namespace Rison.Web.ZJCP.ashx
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class SaveExpDepSet : IHttpHandler
    {
        private DataSet _departs;
        private DataSet _experts;


        public DataSet departs
        {
            get { return _departs; }
            set { _departs = value; }
        }
        public DataSet experts
        {
            get { return _experts; }
            set { _experts = value; }
        }
        public void ProcessRequest(HttpContext context)
        {
            int expertNum = int.Parse(context.Request.Params["expertNum"]);
            int departNum = int.Parse(context.Request.Params["departNum"]);
            findAllDeparts();
            findAllExpert();

            for (int i = 0; i < departNum; i++)
            {
                for(int j=0; j<expertNum; j++){
                    if (!String.IsNullOrEmpty(context.Request.Params[String.Format("exp_{0}_{1}_save", i, j)]))
                    {
                        saveExpDep(i, j);
                    }
                    if (!String.IsNullOrEmpty(context.Request.Params[String.Format("exp_{0}_{1}_delete", i, j)]))
                    {
                        deleteExpDep(i, j);   
                    }
                }
            }

            context.Response.Redirect(String.Format("../ExpertDepartSet.aspx?timestamp={0}", DateTime.Now.ToString("yyyyMMddHHmmssffff")));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        private void saveExpDep(int departIndex, int expertIndex)
        {
            string sql = String.Format("insert into ExpertDepart(exde_id,ex_id,depart_id) values(newid(),'{0}','{1}')", experts.Tables[0].Rows[expertIndex][0], departs.Tables[0].Rows[departIndex][0]);
            DbAccess.executeUpdate(sql);
        }
        private void deleteExpDep(int departIndex, int expertIndex)
        {
            string sql = String.Format("delete from ExpertDepart where ex_id='{0}' and depart_id='{1}'", experts.Tables[0].Rows[expertIndex][0], departs.Tables[0].Rows[departIndex][0]);
            DbAccess.executeUpdate(sql);
        }
        private void findAllDeparts()
        {
            string sql = "select DepartId from Department where ifShow=1 order by orderName";
            departs = DbAccess.executeQuery(sql);
        }
        private void findAllExpert()
        {
            string sql = "select ex_id from expert order by ex_id";
            experts =  DbAccess.executeQuery(sql);
        }
    }
}
